<template>
	<view class="index" ref="poster">
		<!-- 顶部状态栏 -->
		<view :style="{'height': `${statusBarHeight}px`, 'background-color': '#050033'}"></view>
		<!-- 导航栏 -->
		<uni-nav-bar backgroundColor="#050033;" color="#FFF" @clickLeft="goBack" left-icon="left"
			:title="$t('index.text-31')" :border="false" />
		<!-- logo和语言切换 -->
		<view class="logo">
			<image class="logo-ic" src="@/static/logo.png" alt="" />
			<view class="lang-wrap" @click="changeLanguage">
				<image src="../../static/100.png" mode=""></image>
				<text>{{$t('locale.lang')}}</text>
			</view>
		</view>
		<!-- canvas画布 -->
		<canvas canvas-id="myCanvas" class="myCanvas" :style="{
			'width': width + 'px','height': height + 'px', 'position': 'absolute', 'left': '-100%', 'bottom': 0
		}"></canvas>

		<!-- 内容区域 -->
		<!-- #ifdef H5 -->
		<view class="content my_canvas" id="my-canvas" data-type="text" @longpress="handleLongPress">
		<!-- #endif -->
			<!-- #ifdef MP -->
			<view class="content my_canvas" id="my-canvas" data-type="text" @longtap="previewImage">
			<!-- #endif -->
				<!-- 顶部信息 -->
				<view class="top-info my_draw_canvas" data-type="text" data-background="#050033">
					<view class="top-logon my_draw_canvas">
						<view class="block my_draw_canvas" data-type="text" data-background="#d3a86a"></view>
						<image class="logo-ic my_draw_canvas" data-type="image" data-url="../../static/logo.png"
							src="../../static/logo.png" mode=""></image>
					</view>
					<view class="top-title my_draw_canvas">
						<text class="my_draw_canvas" data-type="text"
							:data-text="$t('index.text-34')">{{$t('index.text-34')}}</text>
					</view>
					<view class="top-text my_draw_canvas">
						<text class="my_draw_canvas" data-type="text"
							:data-text="locale == 'zh' ? title : e_title">{{ locale == 'zh' ? title : e_title }}</text>
					</view>
				</view>
				
				<!-- 背景图和线条 -->
				<view class="bg my_draw_canvas" data-delay="1">
					<image class="my_draw_canvas" data-type="image" :data-url="zzdjd_img || '../../static/103.png'"
						:src="zzdjd_img || '../../static/103.png'" mode=""></image>
					<view class="line my_draw_canvas" data-type="text" data-background="#d3a86a"></view>
				</view>
				<!-- data-left -->
				<!-- 信息区域 -->
				<view class="info my_draw_canvas">
					<view class="info-item my_draw_canvas">
						<view class="title my_draw_canvas">
							<text class="my_draw_canvas" data-type="text"
								:data-text="$t('index.text-36') + '：'">{{$t('index.text-36')}}:</text>
						</view>
						<view class="text my_draw_canvas">
							<text class="my_draw_canvas" data-type="inline-text" data-left="10"
								:data-text="`${start | getNowTime} - ${end | getNowTime}`">{{start | getNowTime}} - {{end | getNowTime}}</text>
						</view>
					</view>
					<view class="info-item my_draw_canvas">
						<view class="title my_draw_canvas">
							<text class="my_draw_canvas" data-type="text"
								:data-text="$t('index.text-37') + '：'">{{$t('index.text-37')}}:</text>
						</view>
						<view class="text my_draw_canvas">
							<text class="my_draw_canvas" data-type="inline-text" data-left="10"
								:data-text="en_name">{{en_name}}</text>
						</view>
					</view>
					<view class="info-item my_draw_canvas">
						<view class="title my_draw_canvas">
							<text class="my_draw_canvas" data-type="text"
								:data-text="$t('index.text-38') + '：'">{{$t('index.text-38')}}:</text>
						</view>
						<view class="text my_draw_canvas">
							<text class="my_draw_canvas" data-type="inline-text" data-left="10"
								:data-text="hotel_name">{{hotel_name}}</text>
						</view>
					</view>
					<view class="info-item my_draw_canvas">
						<view class="title my_draw_canvas">
							<text class="my_draw_canvas" data-type="text"
								:data-text="$t('index.text-6') + '：'">{{$t('index.text-6')}}:</text>
						</view>
						<view class="text my_draw_canvas">
							<text class="my_draw_canvas" data-type="inline-text" data-left="10"
								:data-text="depart">{{depart}}</text>
						</view>
					</view>
					<!-- <view class="info-item my_draw_canvas" v-if="isOffice == 0">
					<view class="title my_draw_canvas">
						<text class="my_draw_canvas" data-type="text" :data-text="$t('index.text-10') + '：'">{{$t('index.text-10')}}:</text>
					</view>
					<view class="text my_draw_canvas" v-if="isOffice == 0">
						<text class="my_draw_canvas" data-type="inline-text" data-left="10" :data-text="price">{{price}}</text>
					</view>
				</view> -->
					<!-- <view class="info-item my_draw_canvas">
					<text class="title my_draw_canvas" data-type="text" data-text="自定义题目：">自定义题目：</text>
					<text class="my_draw_canvas" data-type="inline-text" data-text="选择结果或填空结果">选择结果或填空结果</text>
				</view> -->
					<view class="info-item my_draw_canvas">
						<view class="title bank-title my_draw_canvas">
							<view class="line-title my_draw_canvas" data-type="text" data-background="#d3a86a"></view>
							<text class="my_draw_canvas" data-type="text" data-top="1"
								data-text="转账至酒店账号">转账至酒店账号</text>
						</view>
					</view>
					<view class="info-item my_draw_canvas">
						<view class="title my_draw_canvas">
							<text class="my_draw_canvas" data-type="text" data-text="开户行名称：">开户行名称:</text>
						</view>	
						<view class="text my_draw_canvas">
							<text class="my_draw_canvas" data-type="inline-text" data-left="10"
								:data-text="khhmc">{{khhmc}}</text>
						</view>
					</view>
					<view class="info-item my_draw_canvas">
						<view class="title my_draw_canvas">
							<text class="my_draw_canvas" data-type="text" data-text="开户行地址：">开户行地址:</text>
						</view>
						<view class="text my_draw_canvas">
							<text class="my_draw_canvas" data-type="inline-text" data-left="10"
								:data-text="khhdz">{{khhdz}}</text>
						</view>
					</view>
					<view class="info-item my_draw_canvas">
						<view class="title my_draw_canvas">
							<text class="my_draw_canvas" data-type="text" data-text="账户持有人：">账户持有人:</text>
						</view>
						<view class="text my_draw_canvas">				
							<text class="my_draw_canvas" data-type="inline-text" data-left="10"
								:data-text="zhcyr">{{zhcyr}}</text>
						</view>
					</view>
					<view class="info-item my_draw_canvas">
						<view class="title my_draw_canvas">
							<text class="my_draw_canvas" data-type="text" data-text="账号(人民币)：">账号(人民币):</text>
						</view>
						<view class="text my_draw_canvas">
							<text class="my_draw_canvas" data-type="inline-text" data-left="10"
								:data-text="zhrmb">{{zhrmb}}</text>
						</view>
					</view>
					<view class="info-item bank-item my_draw_canvas">
						<view class="title my_draw_canvas">
							<text class="my_draw_canvas" data-type="text" data-text="酒店提供发票为总公司发票：">酒店提供发票为总公司发票:</text>
						</view>
						<view class="text my_draw_canvas">
							<text class="my_draw_canvas" data-type="inline-text" data-left="10"
								:data-text="jdtgfp">{{jdtgfp}}</text>
						</view>
					</view>
				</view>

				<!-- 提示文字 -->
				<view class="cue-text my_draw_canvas">
					<!-- <text class="my_draw_canvas" data-type="inline-text"
						:data-text="$t('index.text-39')">{{$t('index.text-39')}}</text> -->
					<text class="my_draw_canvas" data-type="inline-text"
							:data-text="dibu">{{dibu}}</text>
				</view>
				<!-- 底部信息 -->
				<view class="bottom-info my_draw_canvas">
					<view class="name my_draw_canvas">
						<text class="my_draw_canvas" data-type="text"
							:data-text="$t('index.text-40')">{{$t('index.text-40')}}</text>
					</view>
					<view class="time my_draw_canvas">
						<text class="my_draw_canvas" data-type="text" :data-text="end | getNowTime">{{end | getNowTime}}</text>
					</view>
				</view>
				<!-- 底部线条 -->
				<view class="content-line my_draw_canvas" data-type="text" data-background="#286770"></view>
			</view>
			<!-- 提示 -->
			<view class="cue">
				<image class="cue-ic" src="../../static/104.png" mode=""></image>
				{{$t('index.text-44')}}
			</view>
		</view>
</template>

<script>
	import uniNavBar from "@/uni_modules/uni-nav-bar/components/uni-nav-bar/uni-nav-bar.vue"
	import Wxml2Canvas from "wxml2canvas"
	import html2canvas from 'html2canvas';
	const collection = "hello";
	export default {
		components: {
			uniNavBar
		},
		data() {
			return {
				statusBarHeight: 44,
				base64: '',
				width: 0,
				height: 0,
				poster: '',
				depart: '',
				en_name: '',
				hotel_name: '',
				price: '',
				isOffice: 0,
				title: '',
				e_title: '',
				start: '',
				end: '',
				zzdjd_img: '',
				khhmc: '',
				khhdz: '',
				zhcyr: '',
				zhrmb: '',
				jdtgfp: '',
				dibu: ''
			}
		},
		onLoad(o) {
			
			// 获取状态栏高度
			this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight
			this.depart = o.depart
			this.en_name = o.en_name
			this.hotel_name = o.hotel_name
			this.price = o.price
			this.isOffice = o.isOffice
			this.title = o.title
			this.e_title = o.e_title
			this.start = o.start
			this.end = o.end
			this.zzdjd_img = o.zzdjd_img
			this.khhmc = o.khhmc
			this.khhdz = o.khhdz
			this.zhcyr = o.zhcyr
			this.zhrmb = o.zhrmb
			this.jdtgfp = o.jdtgfp
			this.dibu = o.dibu
		},
		computed: {
			locale() {
				return this.$i18n.locale
			}
		},
		filters: {
			getNowTime(val) {
				let today = new Date(val * 1000);
				let year = today.getFullYear(); // 获取当前年份
				let month = today.getMonth() + 1; // 获取当前月份（注意：月份从 0 开始计数，所以需要加 1）
				let day = today.getDate(); // 获取当前日（几号）
				let hour = today.getHours(); // 获取当前小时
				let minute = today.getMinutes(); // 获取当前分钟
				let second = today.getSeconds(); // 获取当前秒钟
				if (month < 10) {
					month = `0${month}`
				}
				if (day < 10) {
					day = `0${day}`
				}
				// 格式化输出当前时间
				let nowTime = year + '-' + month + '-' + day
				return nowTime
			},
		},
		mounted() {
			this.drawMyCanvas()
		},
		methods: {
			previewImage() {
				if (this.poster != '') {
					this.savePoster(this.poster)
				}
			},
			handleLongPress() {
				// 创建a标签并设置下载链接
				if(this.poster == '') return
				const a = document.createElement('a');
				a.href = this.poster;
				a.style.opacity = 0;
				a.download = 'image.jpg'; // 设置下载文件名

				// 将a标签添加到某个容器中以便触发下载事件（假设有一个容器元素）
				const container = document.querySelector('.index'); // 或者其他选择器来定位容器元素
				container.appendChild(a); // 确保a标签被添加到DOM中
				// 保存对resolve的引用，以便稍后使用
				const downloadResolver = resolve => {
					a.addEventListener('click', resolve, {
						once: true
					});
				};
				// 创建Promise来处理下载完成后的清理工作
				const downloadPromise = new Promise(downloadResolver);

				// 模拟点击事件以触发下载（如果不需要立即触发下载，这一步可以省略）
				a.click(); // 如果不需要立即触发下载可以移除这一行

				// 下载完成后清理（确保只有在父节点存在时才尝试移除元素）
				downloadPromise.then(() => {
					if (a && a.parentNode) { // 确保a标签及其父节点存在
						// 清除事件监听器（这里应该传递事件处理函数而不是resolve函数）
						a.removeEventListener('click', downloadResolver
						.resolve); // 注意这里应该是resolve函数本身而不是调用resolve()的函数返回值（通常是undefined）
						// 移除a标签
						a.parentNode.removeChild(a); // 确保只有在父节点存在时才调用removeChild方法
					} else {
						console.error('Element or its parent does not exist'); // 输出错误信息帮助调试问题根源
					}
				});
			},

			// 绘制图片
			drawMyCanvas() {
				wx.showLoading()
				const that = this

				// #ifdef H5
				let docStyle = document.querySelector('#my-canvas').style
				that.width = docStyle.width
				that.height = docStyle.width
				setTimeout(() => {
					that.starHtmlDraw()
				}, 1500);
				// #endif

				// #ifdef MP
				const query = wx.createSelectorQuery().in(this);
				query.select('#my-canvas').fields({ // 选择需要生成canvas的范围
					size: true,
					scrollOffset: true
				}, data => {
					let width = data.width;
					let height = data.height;
					that.width = width
					that.height = height
					setTimeout(() => {
						that.startDraw()
					}, 1500);
				}).exec()
				// #endif

			},
			starHtmlDraw() {
				const t = this;
				const opts = {
					useCORS: true,
					allowTaint: true,
					scale: 2, //按比例增加分辨率 (2=双倍).
					dpi: 96, //设备像素比
					scrollY: 0
				};
				html2canvas(document.querySelector('#my-canvas'), opts)
					.then(canvas => {
						wx.hideLoading()
						let baseImg = canvas.toDataURL('image/png'); //a标签通过 canvas 转base64
						t.poster = baseImg
					})
					.catch(err => {
						wx.hideLoading()
						console.log('html2canvas', err);
					});
			},
			startDraw() {
				let that = this

				// 创建wxml2canvas对象
				let drawMyImage = new Wxml2Canvas({
					element: 'myCanvas', // canvas的id,
					obj: that, // 传入当前组件的this
					width: that.width * 2,
					height: that.height * 2,
					background: '#fff', // 生成图片的背景色
					logging: false, //日志
					scrollY: 0,
					scrollX: 0,
					useCORS: true, //跨域
					allowTaint: true,
					progress(percent) { // 进度
						// console.log(percent);
					},
					finish(url) { // 生成的图片
						wx.hideLoading()
						that.poster = url
						// that.savePoster(url)
					},
					error(res) { // 失败原因
						console.log(res);
						wx.hideLoading()
					}
				}, this);
				let data = {
					// 获取wxml数据
					list: [{
						type: 'wxml',
						class: '.my_canvas .my_draw_canvas', // my_canvas要绘制的wxml元素根类名， **my_draw_canvas**单个元素的类名（所有要绘制的单个元素都要添加该类名）
						limit: '.my_canvas', // 要绘制的wxml元素根类名
						x: 0,
						y: 0
					}]
				}
				// 绘制canvas
				drawMyImage.draw(data, this);
			},
			// 保存
			savePoster(url) {
				const that = this
				wx.saveImageToPhotosAlbum({
					filePath: url,
					success: function() {
						wx.showToast({
							title: that.$t('index.text-50'),
							icon: 'none',
							duration: 1500
						});
					},
					fail(err) {
						if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg ===
							"saveImageToPhotosAlbum:fail auth deny" || err.errMsg ===
							"saveImageToPhotosAlbum:fail authorize no response") {
							wx.showModal({
								title: '提示',
								content: '需要您授权保存相册',
								showCancel: false,
								success: modalSuccess => {
									wx.openSetting({
										success(settingdata) {
											if (settingdata.authSetting[
													'scope.writePhotosAlbum']) {
												wx.saveImageToPhotosAlbum({
													filePath: that.imgUrl,
													success: function() {
														wx.showToast({
															title: '保存成功',
															icon: 'success',
															duration: 2000
														})
													},
												})
											} else {
												wx.showToast({
													title: '授权失败，请稍后重新获取',
													icon: 'none',
													duration: 1500
												});
											}
										}
									})
								}
							})
						}
					}
				})
			},
			goBack() {
				uni.navigateBack()
			},
			changeLanguage() {
				if (this.$i18n.locale == 'zh') {
					this.$i18n.locale = 'en';
					uni.setStorageSync('locale', 'en')
				} else {
					this.$i18n.locale = 'zh';
					uni.setStorageSync('locale', 'zh')
				}
				this.drawMyCanvas()
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f3f3f3;
	}

	.uni-navbar {
		background-color: #050033 !important;
	}

	.index {
		position: relative;
		padding-bottom: 110upx;
		box-sizing: border-box;

		.logo {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20upx 30upx;
			margin-bottom: 30upx;
			background-color: #050033;

			.logo-ic {
				width: 78upx;
				height: 64upx;
			}

			.lang-wrap {
				display: flex;
				align-items: center;
				color: #fff;
				font-size: 24upx;

				image {
					width: 30upx;
					height: 30upx;
					margin-right: 12upx;
				}
			}
		}

		.content {
			margin: 0 30upx;
			background-color: #fff;


			.top-info {
				width: 100%;
				height: 420upx;
				background-color: #050033;
				padding-left: 30upx;
				box-sizing: border-box;

				.top-logon {
					.block {
						width: 82upx;
						height: 34upx;
						background-color: #d3a86a;
					}

					.logo-ic {
						margin-top: 14upx;
						margin-bottom: 60upx;
						display: block;
						width: 78upx;
						height: 64upx;
					}
				}

				.top-title {
					font-size: 36upx;
					color: #fff;
					padding-bottom: 32upx;
				}

				.top-text {
					font-size: 30upx;
					color: #d3a86a;
				}
			}

			.bg {
				display: flex;
				flex-direction: column;
				align-items: flex-end;
				position: relative;
				top: -80upx;
				z-index: 10;

				image {
					width: 650upx;
					height: 402upx;
				}

				.line {
					width: 650upx;
					height: 10upx;
					background-color: #d3a86a;
				}
			}

			.info {
				padding: 0 34upx;
				box-sizing: border-box;

				.info-item {
					display: flex;
					align-items: center;
					padding-bottom: 20upx;
					font-size: 24upx;
					color: #333333;

					.title {
						flex-shrink: 0;
						padding: 0 8upx 0 0;

						&.bank-title {
							color: #050033;
							margin-top: 28upx;
							display: flex;
							align-items: flex-start;
							line-height: 24upx;

							.line-title {
								width: 4upx;
								height: 24upx;
								background-color: #d3a86a;
								margin-right: 14upx;
							}

							.text {
								color: #333333;
								line-height: 26upx;
							}
						}
					}

					&.bank-item {
						margin-top: 28upx;

						.title,
						.text {
							color: #333333;
						}
					}

					&.margin-28 {
						margin-bottom: 28upx;
					}
				}
			}

			.cue-text {
				margin-bottom: 50upx;
				padding: 0 34upx;
				box-sizing: border-box;
				font-size: 24upx;
				color: #333333;
			}

			.bottom-info {
				padding: 0 34upx;
				box-sizing: border-box;
				text-align: right;
				padding-bottom: 80upx;
				font-size: 24upx;
				color: #333333;
			}

			.content-line {
				width: 100%;
				height: 10upx;
				background-color: #286770;
			}
		}

		.cue {
			margin-top: 40upx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			font-size: 24upx;
			color: #666666;

			.cue-ic {
				width: 37upx;
				height: 55upx;
				margin-bottom: 24upx;
			}
		}
	}
</style>